<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/7
 * Time: 19:12
 */

namespace App\Game\Traits;


trait YcTrait
{
    public function ycRequest($method,$url, $action)
    {
        $tick = time();
        $post=[];
        $post['Timestamp'] = $tick;
        $post['MerchantId'] = $this->merchantId;
        $post['Data'] =  openssl_encrypt(json_encode($action),'AES-256-ECB',$this->aesKey);;
        $key = $post['Timestamp'].$post['MerchantId'].$post['Data'].$this->sha1Key;
        $post['Key'] = bin2hex(sha1($key, true));
        $result=$this->request($method, $url, $post, $this->header);
//        file_put_contents('/home/gameapi/storage/logs/test.log', 'res...'.$result.PHP_EOL, FILE_APPEND);
        //解密
        $result = json_decode($result, true);
        if (isset($result['Error']) && $result['Error'] == 0){
            $result['Data'] = openssl_decrypt($result['Data'],'AES-256-ECB',$this->aesKey);
            $result['Data'] = json_decode($result['Data'],true);
        }
        return $result;
    }

    public function apiDataParse(array $apiData, array $data)
    {
        $data = $this->usernameParse($apiData, $data);
        return $data;
    }

    private function usernameParse(array $apiData, array $data)
    {
        if (array_key_exists('PlayerName', $apiData)) {
            //去掉前缀
            $data['username'] = str_replace($this->merchantId.'@','',$apiData['PlayerName']);
        }
        return $data;
    }
}
